#import "JokePageCell.h"
#import "JokeReplyModel.h"
#import "DBManager.h"
#import "JokeReplyCell.h"
#import "MTLabel.h"
#import "UserManager.h"
#import "NSData+Base64.h"
#import "NetWorkManager.h"
#import "UIImageView+WebCache.h"
#import "NSString+Md5String.h"
#import "FileManager.h"

@implementation JokePageCell

@synthesize scanPhotos,owner,jokePlaying,jokeManagerPlaying;
@synthesize mainView,jokeInfoView,funnyBtn,unfunnyBtn,funnyNum,unfunnyNum;
@synthesize likeStateLoading,likeStateEnable,likeStateDisable;
@synthesize currentLikeState,userStateLogin,userStateLogout,currentUserState;

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        //
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self){
        CGRect realFrame = self.frame;
        realFrame.size.height = WINDOW_HEIGHT - 46;
        self.frame = realFrame;
        self.likeStateLoading = [[JPCLikeStateLoading alloc]init:self];
        self.likeStateEnable = [[JPCLikeStateEnable alloc]init:self];
        self.likeStateDisable = [[JPCLikeStateDisable alloc]init:self];
        self.userStateLogin = [[JPCUserStateLogin alloc]init:self];
        self.userStateLogout = [[JPCUserStateLogout alloc]init:self];
    }
    return self;
}

- (void)dealloc {
    PP_RELEASE(jokeView);
    PP_RELEASE(jokeText);
    PP_RELEASE(jokeImg);
    PP_RELEASE(jokeImg);
//    PP_RELEASE(jokeImgBtn);
    PP_RELEASE(jokeWebViewContainer);
    PP_RELEASE(jokeWebView);
    PP_RELEASE(userName);
    PP_RELEASE(replyTable);
    PP_RELEASE(jokeViewBg);
    PP_RELEASE(jokeReplyView);
    PP_RELEASE(jokeReplyViewBg);
    PP_RELEASE(jokeReplyCount);
    PP_RELEASE(indicator);
    PP_RELEASE(gap);
    PP_RELEASE(jokePlaying);
    PP_RELEASE(jokeManagerPlaying);
    PP_RELEASE(mainView);
    PP_RELEASE(jokeInfoView);
    PP_RELEASE(funnyBtn);
    PP_RELEASE(unfunnyBtn);
    PP_RELEASE(funnyNum);
    PP_RELEASE(unfunnyNum);
    PP_RELEASE(likeStateLoading);
    PP_RELEASE(likeStateEnable);
    PP_RELEASE(likeStateDisable);
    PP_RELEASE(likeStateLoading);
    PP_RELEASE(userStateLogin);
    PP_RELEASE(userStateLogout);
    PP_RELEASE(browserPhotos);
    [super dealloc];
}

- (void)setData:(BaseUIViewController<JokePageCellDelegate> *)pOwner :(JokeModel *)pJoke :(JokeManager *)pJokeManager {
    self.owner = pOwner;
    self.jokePlaying = pJoke;
    self.jokeManagerPlaying = pJokeManager;
    
    jokeReplyView.alpha = 0.0f;
    
    userName.text = pJoke.userName;
    funnyNum.text = [NSString stringWithFormat:@"+%d",pJoke.goodNum];
    funnyNum.tag = pJoke.goodNum;
    unfunnyNum.text = [NSString stringWithFormat:@"-%d",pJoke.badNum];
    unfunnyNum.tag = pJoke.badNum;
    
    jokeImg.image = nil;
    jokeImg.hidden = YES;
//    jokeImgBtn.hidden = YES;
    jokeWebView.delegate = nil;
    jokeWebView.scalesPageToFit = YES;
    jokeWebView.dataDetectorTypes = UIDataDetectorTypeNone;
    jokeWebView.backgroundColor = [UIColor clearColor];
    [jokeWebView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML='';"];
    jokeWebView.hidden = YES;
    jokeWebViewContainer.hidden = YES;
    
    [jokeText removeFromSuperview];
    jokeText = [[[UIWebView alloc] initWithFrame:CGRectMake(15, 15, 290, 1)] autorelease];
    jokeText.userInteractionEnabled = NO;
    jokeText.delegate = self;
    [jokeView addSubview:jokeText];
    //下面两行协助 UIWebView 背景透明化，这两属性可以在 xib 中进行设置
    jokeText.backgroundColor = [UIColor clearColor];  //但是这个属性必须用代码设置，光 xib 设置不行
    jokeText.opaque = NO;
    //这行能在模拟器下明下加快 loadHTMLString 后显示的速度，其实在真机上没有下句也感觉不到加载过程
    jokeText.dataDetectorTypes = UIDataDetectorTypeNone;
    //下面的 backgroud-color:transparent 结合最前面的两行代码指定的属性就真正使得 WebView 的背景透明了
    //而后的 font:16px/18px 就是设置字体大小为 16px, 行间距为 18px，也可用  line-height: 18px 单独设置行间距
    //最后的 Custom-Font-Name 就是前面在项目中加上的字体文件所对应的字体名称了
    NSString *webviewText = @"<style>body{margin:0;background-color:transparent;font:16px/25px Custom-Font-Name}</style>";
    NSString * htmlString = [pJoke.jokeText stringByReplacingOccurrencesOfString:@"\r\n"    withString:@"<br />"];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"\n"                     withString:@"<br />"];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"\r"                     withString:@"<br />"];
    
    mainView.delegate = self;
    
    indicator.alpha = 0;
    
    replyTable.delegate = nil;
    replyTable.dataSource = nil;
    replyTable.scrollsToTop    = NO;
    [replyTable reloadData];
    jokeReplyCount.text = [NSString stringWithFormat:@""];
    
    [jokeText loadHTMLString:[webviewText stringByAppendingFormat:@"%@", htmlString] baseURL:nil]; //在 WebView 中显示本地的字符串
}

#pragma mark - UIWebview delegete

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    float labelHeight = [[jokeText stringByEvaluatingJavaScriptFromString: @"document.body.scrollHeight"] floatValue];
    CGRect textFrame = jokeText.frame;
    textFrame.size.height = labelHeight;
    jokeText.frame = textFrame;
    if( jokePlaying.jokeImgUrl.length == 0 ){
        [self rebuildView];
        return;
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            jokeImg.hidden = NO;
            jokeImg.image = [UIImage imageNamed:@"loading_success.png"];
            [self rebuildView];
        });
        if (PP_hasWifi || PP_HasNoWifiButLoadImages) {
            JokeModel *tJoke = [jokePlaying copy];
            if([[tJoke.jokeImgUrl lowercaseString] hasSuffix:@"gif"] ){
                NSArray *array = [tJoke.jokeImgUrl componentsSeparatedByString:@"/"];
                NSString *gifImgName = [NSString stringWithFormat:@"%@",[array objectAtIndex:[array count]-1]];
                NSString *imgFilePath = [SD_CACHES_FOLDER stringByAppendingPathComponent:gifImgName];
                NSString *gifImgNameSmall = [NSString stringWithFormat:@"small_%@",[array objectAtIndex:[array count]-1]];
                BOOL gifExsit = [[FileManager sharedInstance]imageExsit:gifImgName andFolder:SD_CACHES_FOLDER];
                BOOL gifExsitSmall = [[FileManager sharedInstance]imageExsit:gifImgNameSmall andFolder:SD_CACHES_FOLDER];
                if (gifExsit && gifExsitSmall) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if(![jokePlaying.jokeId isEqual: tJoke.jokeId]){
                            [tJoke release];
                            return;
                        }
                        jokeImg.image = [UIImage imageWithContentsOfFile:imgFilePath];
                        jokeImg.hidden = YES;
//                        jokeImgBtn.hidden = YES;
                        
                        float iw = jokeImg.image.size.width;
                        float ih = jokeImg.image.size.height;
                        float ow = 308;
                        float oh = ow*ih/iw;
                        __block CGRect containerFrame = jokeWebViewContainer.frame;
                        containerFrame.origin.x = iw<308?(jokeView.frame.size.width-jokeImg.image.size.width)/2:5;
                        containerFrame.size.width = MIN(ow,iw);
                        containerFrame.size.height = MIN(oh,ih);
                        jokeWebViewContainer.frame = containerFrame;
                        jokeWebView.frame = CGRectMake(0, 0, containerFrame.size.width, containerFrame.size.height);
                        NSString *htmlStr =[NSString stringWithFormat:@"<html><head></head><body><img src='file://%@' width=100%% height=100%%></body></html>",imgFilePath];
                        NSLog(@"html str :%@",htmlStr);
                        [jokeWebView loadHTMLString:htmlStr baseURL:nil];
                        jokeWebView.hidden = NO;
                        jokeWebViewContainer.hidden = NO;
                        [self rebuildView];
                        [tJoke release];
                    });
                }else{
                    NSData *gifData = [NSData dataWithContentsOfURL:[NSURL URLWithString:tJoke.jokeImgUrl]];        
                    BOOL success = [[FileManager sharedInstance]saveGif:gifData withUrl:tJoke.jokeImgUrl];
                    UIImage *imageSmall = [UIImage imageWithData:gifData];
                    NSString *smallimgFilePath = [SD_CACHES_FOLDER stringByAppendingPathComponent:[NSString stringWithFormat:@"small_%@",gifImgName]];
                    NSLog(@"imgFilePath gif_small------ :%@",smallimgFilePath);
                    NSData *imageData = UIImageJPEGRepresentation(imageSmall, 0.5);
                    Log(@"%@",smallimgFilePath);
                    NSError *err = nil;
                    BOOL writeSucces = NO;
                    if ( [imageData writeToFile:smallimgFilePath options:NSAtomicWrite error:&err]) {
                        NSLog(@"gif缩略图 write success :%@",err);
                        writeSucces = YES;
                    }else{
                        NSLog(@"gif缩略图 write failed :%@",err);
                        writeSucces = NO;
                    }
                    if (success && writeSucces) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if(![jokePlaying.jokeId isEqual: tJoke.jokeId]){
                                [tJoke release];
                                return;
                            }
                            
                            jokeImg.image = [UIImage imageNamed:@"loading_success.png"];
                            jokeImg.hidden = YES;
//                            jokeImgBtn.hidden = YES;
                            
                            float iw = jokeImg.image.size.width;
                            float ih = jokeImg.image.size.height;
                            float ow = 308;
                            float oh = ow*ih/iw;
                            __block CGRect containerFrame = jokeWebViewContainer.frame;
                            containerFrame.origin.x = iw<308?(jokeView.frame.size.width-jokeImg.image.size.width)/2:5;
                            containerFrame.size.width = MIN(ow,iw);
                            containerFrame.size.height = MIN(oh,ih);
                            jokeWebViewContainer.frame = containerFrame;
                            jokeWebView.frame = CGRectMake(0, 0, containerFrame.size.width, containerFrame.size.height);
                            NSString *htmlStr =[NSString stringWithFormat:@"<html><head></head><body><img src='file://%@' width=100%% height=100%%></body></html>",imgFilePath];
                            NSLog(@"html str :%@",htmlStr);
                            [jokeWebView loadHTMLString:htmlStr baseURL:nil];
                            jokeWebView.hidden = NO;
                            jokeWebViewContainer.hidden = NO;
                            [self rebuildView];
                            [tJoke release];
                        });
                    }else{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            jokeImg.image = [UIImage imageNamed:@"loading_false.png"];
//                            jokeImgBtn.hidden = NO;
                            [self rebuildView];
                            [tJoke release];
                        });
                    }
                }
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(![jokePlaying.jokeId isEqual: tJoke.jokeId]){
                        [tJoke release];
                        return;
                    }
                    jokeImg.image = [UIImage imageNamed:@"loading_success.png"];
                    jokeUrlForMd5 = tJoke.jokeImgUrl;
                    SDWebImageManager *manager = [SDWebImageManager sharedManager];
                    [manager downloadWithURL:[NSURL URLWithString:tJoke.jokeImgUrl] delegate:self];
            
    //                browserPhotos = [[NSMutableArray alloc] init];
    //                MWPhoto *mwphoto = [MWPhoto photoWithImage:tJoke.jokeImgFull];
    //                [browserPhotos addObject:mwphoto];
    //                self.scanPhotos = browserPhotos;
    //                
    //                jokeImg.image = tJoke.jokeImgFull;
                    jokeWebViewContainer.hidden = YES;
                    jokeImg.hidden = NO;
    //                jokeImgBtn.hidden = NO;
                    [self rebuildView];
                    [tJoke release];
                });
            }
        }
    });
}

- (void)scanBigPhoto {
    [owner baseHideComment];
    [owner JPCscanPhotos];
}

- (void)rebuildView {
    CGRect jokeFrame = jokeView.frame;
    CGRect textFrame = jokeText.frame;
    float labelHeight = textFrame.size.height;
    
    CGRect imgFrame;
    if( jokeImg.image != nil ){
        if (jokeImg.image.size.width < 308) {
            imgFrame = CGRectMake((jokeFrame.size.width-jokeImg.image.size.width)/2,textFrame.origin.y+labelHeight+5,jokeImg.image.size.width,jokeImg.image.size.height);
            if(jokeImg.image.size.width < 290){
                //添加边框
                CALayer * iLayer = [jokeImg layer];
                iLayer.borderColor = [UIColorFromRGB(0xd9dcdd, 1.0f) CGColor];
                iLayer.borderWidth = 1.0f;
                CALayer * wLayer = [jokeWebViewContainer layer];
                wLayer.borderColor = [UIColorFromRGB(0xd9dcdd, 1.0f) CGColor];
                wLayer.borderWidth = 1.0f;
            }else{
                //去掉边框
                CALayer * iLayer = [jokeImg layer];
                iLayer.borderColor = [[UIColor clearColor] CGColor];
                iLayer.borderWidth = 0.0f;
                CALayer * wLayer = [jokeWebViewContainer layer];
                wLayer.borderColor = [[UIColor clearColor] CGColor];
                wLayer.borderWidth = 0.0f;
            }
        } else {
            imgFrame = CGRectMake(5,textFrame.origin.y+labelHeight+5,308,308*jokeImg.image.size.height/jokeImg.image.size.width);
            //去掉边框
            CALayer * iLayer = [jokeImg layer];
            iLayer.borderColor = [[UIColor clearColor] CGColor];
            iLayer.borderWidth = 0.0f;
            CALayer * wLayer = [jokeWebViewContainer layer];
            wLayer.borderColor = [[UIColor clearColor] CGColor];
            wLayer.borderWidth = 0.0f;
        }        
    }else{
        imgFrame = CGRectZero;
    }
    
    if( !jokeWebViewContainer.hidden ){
        jokeWebViewContainer.frame = imgFrame;
    } else if( !jokeImg.hidden ){
        jokeImg.frame = imgFrame;
//        jokeImgBtn.frame = imgFrame;
    }
    
    CGRect jokeInfoViewFrame =  jokeInfoView.frame;
    jokeInfoViewFrame.origin.y = textFrame.origin.y + labelHeight +5 + imgFrame.size.height + 10;
    jokeInfoView.frame = jokeInfoViewFrame;
    
    CGRect jokeViewBgFrame = jokeViewBg.frame;
    jokeViewBgFrame.size.height = jokeInfoViewFrame.origin.y + jokeInfoViewFrame.size.height + 5 - jokeViewBgFrame.origin.y;
    jokeViewBg.frame = jokeViewBgFrame;
    jokeViewBg.image = [[UIImage imageNamed:@"joke_page_bg.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
    
    CGRect gapFrame = gap.frame;
    gapFrame.origin.y = jokeViewBgFrame.origin.y + jokeViewBgFrame.size.height;
    gap.frame  = gapFrame;
    
    jokeFrame.size.height = gap.frame.origin.y + gap.frame.size.height;
    jokeView.frame = jokeFrame;
    
    CGRect replyTableFrame = replyTable.frame;
    replyTableFrame.size.height = replyTable.contentSize.height;
    replyTable.frame = replyTableFrame;
    
    CGRect jokeReplyFrame = jokeReplyView.frame;
    jokeReplyFrame.origin.y = jokeFrame.origin.y + jokeFrame.size.height;
    jokeReplyFrame.size.height = replyTableFrame.origin.y + replyTableFrame.size.height + 10;
    jokeReplyView.frame = jokeReplyFrame;
    jokeReplyViewBg.image = [[UIImage imageNamed:@"joke_page_bg.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
    
    CGSize mainContentFrame = mainView.contentSize;
    mainContentFrame.height = jokeReplyFrame.origin.y + jokeReplyFrame.size.height + 80;
    mainView.contentSize = mainContentFrame;
}

- (void)setMoreData {
    indicator.animationDuration = 0.8;
    indicator.animationImages = [NSArray arrayWithObjects:
                                 [UIImage imageNamed:@"fan_1.png"],
                                 [UIImage imageNamed:@"fan_2.png"],
                                 [UIImage imageNamed:@"fan_3.png"],
                                 [UIImage imageNamed:@"fan_4.png"],
                                 [UIImage imageNamed:@"fan_5.png"],
                                 [UIImage imageNamed:@"fan_6.png"],
                                 [UIImage imageNamed:@"fan_7.png"],
                                 [UIImage imageNamed:@"fan_8.png"],
                                 nil];
    [indicator startAnimating];
    [UIView animateWithDuration:0.5f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         indicator.alpha = 1;
                     }
                     completion:^(BOOL bl){
                         [indicator stopAnimating];
                         indicator.animationDuration = 0.4;
                         [indicator startAnimating];
                     }];
    NSString *loadingId = [NSString stringWithFormat:@"%@",jokePlaying.jokeId];
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration : 0.3f
                              delay : 0
                            options : UIViewAnimationOptionCurveEaseIn
                         animations : ^{
                             jokeReplyView.alpha = 1.0f;
                         }
                         completion : ^(BOOL bl){
                         }];
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(1);
        if(![loadingId isEqualToString:jokePlaying.jokeId]){
            Log(@"cell changed");
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            jokeReplyCount.text = [NSString stringWithFormat:@"%d条评论",jokePlaying.replies.count];
            replyTable.delegate = self;
            replyTable.dataSource = self;
            [replyTable reloadData];
            CGRect replyTableFrame = replyTable.frame;
            replyTableFrame.size.height = replyTable.contentSize.height;
            replyTable.frame = replyTableFrame;
            CGRect jokeReplyFrame = jokeReplyView.frame;
            jokeReplyFrame.origin.y = jokeView.frame.origin.y + jokeView.frame.size.height;
            jokeReplyFrame.size.height = replyTableFrame.origin.y + replyTableFrame.size.height + 10;
            jokeReplyView.frame = jokeReplyFrame;
            jokeReplyViewBg.image = [[UIImage imageNamed:@"joke_page_bg.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
            CGSize mainContentFrame = mainView.contentSize;
            mainContentFrame.height = jokeReplyFrame.origin.y + jokeReplyFrame.size.height + 80;
            mainView.contentSize = mainContentFrame;
            
            float timeNow = [[NSDate date] timeIntervalSince1970];
            if( timeNow - self.jokePlaying.replyRequestTime < 3 * 60 && self.jokePlaying.replies.count > 5 ){
                [UIView animateWithDuration : 0.3f
                                      delay : 0
                                    options : UIViewAnimationOptionCurveEaseIn
                                 animations : ^{
                                     indicator.alpha = 0;
                                 }
                                 completion : ^(BOOL bl){
                                     [indicator stopAnimating];
                                 }];
            }else{
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    @autoreleasepool {
                        NSMutableArray *tReplies = [jokeManagerPlaying httpGetReplySync:jokePlaying.jokeId];
                        if(![loadingId isEqualToString:self.jokePlaying.jokeId]){
                            Log(@"cell changed");
                            return;
                        }
                        self.jokePlaying.replies = [[NSMutableArray alloc] init];
                        for( JokeReplyModel *one in tReplies){
                            [self.jokePlaying.replies addObject:one];
                        }
                        self.jokePlaying.replyRequestTime = timeNow;
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if(![loadingId isEqualToString:self.jokePlaying.jokeId]){
                            Log(@"cell changed");
                            return;
                        }
                        [replyTable reloadData];
                        jokeReplyCount.text = [NSString stringWithFormat:@"%d条评论",jokePlaying.replies.count];
                        CGRect replyTableFrame = replyTable.frame;
                        replyTableFrame.size.height = replyTable.contentSize.height;
                        replyTable.frame = replyTableFrame;
                        CGRect jokeReplyFrame = jokeReplyView.frame;
                        jokeReplyFrame.origin.y = jokeView.frame.origin.y + jokeView.frame.size.height;
                        jokeReplyFrame.size.height = replyTableFrame.origin.y + replyTableFrame.size.height + 10;
                        jokeReplyView.frame = jokeReplyFrame;
                        jokeReplyViewBg.image = [[UIImage imageNamed:@"joke_page_bg.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
                        CGSize mainContentFrame = mainView.contentSize;
                        mainContentFrame.height = jokeReplyFrame.origin.y + jokeReplyFrame.size.height + 80;
                        mainView.contentSize = mainContentFrame;
                        [UIView animateWithDuration : 0.3f
                                              delay : 0
                                            options : UIViewAnimationOptionCurveEaseIn
                                         animations : ^{
                                             indicator.alpha = 0;
                                         }
                                         completion : ^(BOOL bl){
                                             [indicator stopAnimating];
                                         }];
                        [self findMisbehavingScrollViews];
                        mainView.scrollsToTop = YES;
                    });
                    self.jokePlaying.replyNum = jokePlaying.replies.count;
                    [[DBManager sharedInstance] updateJoke:jokeManagerPlaying.dbSort :jokePlaying];
                });
            }
        });
    });
    
    if( (jokePlaying.liked<0 || jokePlaying.unliked<0 ) && [UserManager sharedInstance].isLogin){
        [self setLikeState:self.likeStateLoading];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            int isLiked = [jokeManagerPlaying httpIsLikedSync:jokePlaying.jokeId];
            int isUnliked = [jokeManagerPlaying httpIsUnlikedSync:jokePlaying.jokeId];
            dispatch_async(dispatch_get_main_queue(), ^{
                if(![loadingId isEqual:jokePlaying.jokeId]){
                    Log(@"cell changed");
                    return;
                }
                JokeModel *tJoke = jokePlaying;
                if (isLiked>=0 || isUnliked>=0) {
                    tJoke.liked = isLiked;
                    tJoke.unliked = isUnliked;
                    [self setLikeState:self.likeStateDisable];
                }else{
                    [self setLikeState:self.likeStateEnable];
                }
                [[DBManager sharedInstance] updateJoke:jokeManagerPlaying.dbSort :tJoke];
                [tJoke release];
            });
        });
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            if(![loadingId isEqual:jokePlaying.jokeId]){
                Log(@"cell changed");
                return;
            }
            if (jokePlaying.liked || jokePlaying.unliked) {
                [self setLikeState:self.likeStateDisable];
            }else{
                [self setLikeState:self.likeStateEnable];
            }
        });
    }
}

- (void)findMisbehavingScrollViews
{
    UIView *view = [[UIApplication sharedApplication] keyWindow];
    [self findMisbehavingScrollViewsIn:view];
}

- (void)findMisbehavingScrollViewsIn:(UIView *)view
{
    if ([view isKindOfClass:[UIScrollView class]])
    {
        NSLog(@"Found UIScrollView: %@", view);
        if ([(UIScrollView *)view scrollsToTop])
        {
            NSLog(@"scrollsToTop = YES!");
            [(UIScrollView *)view setScrollsToTop:NO];
        }
    }
    for (UIView *subview in [view subviews])
    {
        [self findMisbehavingScrollViewsIn:subview];
    }
}


- (void)refreshNum:(int)funny :(int)unfunny :(int)reply {
    dispatch_async(dispatch_get_main_queue(), ^{
        funnyNum.text = [NSString stringWithFormat:@"+%d",funny];
        funnyNum.tag = funny;
        unfunnyNum.text = [NSString stringWithFormat:@"-%d",unfunny];
        unfunnyNum.tag = unfunny;
    });
}

- (void)toTop {
    CGPoint offset = mainView.contentOffset;
    offset.y = 0;
    mainView.contentOffset = offset;
}

- (void)reply {
    [replyTable reloadData];
    jokeReplyCount.text = [NSString stringWithFormat:@"%d条评论",jokePlaying.replies.count];
    [self rebuildView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = 0;
    if(jokePlaying!=nil && jokePlaying.replies!=nil){
        count = [jokePlaying.replies count];
    }
    Log(@"JPC replies : %d", count);
    return count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *jodeCellIdentifier = @"JokeReplyCell";
    JokeReplyCell *cell = (JokeReplyCell *)[replyTable dequeueReusableCellWithIdentifier:jodeCellIdentifier];
    if (cell==nil)
    {
        NSArray *nibList = [[NSBundle mainBundle] loadNibNamed:jodeCellIdentifier owner:self options:nil];
        for(id obj in nibList)
        {
            if([obj isKindOfClass:[JokeReplyCell class]])
            {
                cell=(JokeReplyCell *)obj;
            }
        }
    }
    if( indexPath.row >= jokePlaying.replies.count){
        Log(@"~~~~~~~~~~~~~~why find %d in %d",indexPath.row,jokePlaying.replies.count);
        return nil;
    }
    JokeReplyModel *tReply = [jokePlaying.replies objectAtIndex:indexPath.row];
    // TODO 2 :
    if( cell.retainCount>0 ){
        [cell setReplyText:tReply.replyText withName:tReply.replyName withFloor:[NSString stringWithFormat:@"%dF",indexPath.row+1]];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // TODO 1 :
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* touch = [touches anyObject];
    CGPoint pt = [touch locationInView:self];
    if(CGRectContainsPoint(owner.baseCommentView.frame,pt)){
    }else{
        [owner baseHideComment];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    static BOOL hidden = NO;
    static int gapping = 40;
    static int lastContentOffset = 40;
    ScrollDirection scrollDirection;
    
    [owner baseHideComment];
    if(sender.contentOffset.y == 0 ){
        if( hidden ){
            Log(@"top");
            hidden = NO;
            [owner JPCup];
        }
    } else if(sender.contentSize.height - 80 - gapping - sender.contentOffset.y <= sender.frame.size.height){
        if( hidden ){
            Log(@"bottom");
            hidden = NO;
            [owner JPCup];
        }
    }else if (lastContentOffset - sender.contentOffset.y > gapping){
        scrollDirection = ScrollDirectionUp;
        if( hidden ){
            Log(@"up");
            hidden = NO;
            [owner JPCup];
        }
    }else if (sender.contentOffset.y - lastContentOffset > gapping){
        scrollDirection = ScrollDirectionDown;
        if( !hidden ){
            Log(@"down");
            hidden = YES;
            [owner JPCdown];
        }
    }
    if( fabs(lastContentOffset-sender.contentOffset.y)>=gapping ){
        lastContentOffset = sender.contentOffset.y;
    }
}

- (IBAction)pressFunnyBtn:(id)sender {
    HAS_NO_NETWORK(owner);
    [currentUserState JPCUSlike];
}

- (IBAction)pressUnfunnyBtn:(id)sender {
    HAS_NO_NETWORK(owner);
    [currentUserState JPCUSunlike];
}

- (void)setLikeState:(JPCLikeStateBase *)newState {
    dispatch_async(dispatch_get_main_queue(), ^{
        currentLikeState = newState;
        [currentLikeState JPCLSstart];
    });
}

- (void)setUserState:(JPCUserStateBase *)newState{
    dispatch_async(dispatch_get_main_queue(), ^{
        currentUserState = newState;
    });
}



// Called on main
- (void)imageDidFinishLoadingSoDecompress {
    if (jokeImg) {
        [[SDWebImageDecoder sharedImageDecoder] decodeImage:jokeImg.image withDelegate:self userInfo:nil];
    }
}
#pragma makr -
#pragma mark -------SDWebImage Delegate------
// Called on main
- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image {
    
    browserPhotos = [[NSMutableArray alloc] init];
    MWPhoto *mwphoto = [MWPhoto photoWithImage:image];
    [browserPhotos addObject:mwphoto];
    self.scanPhotos = browserPhotos;
    
    jokeImg.image = image;
//    jokeWebViewContainer.hidden = YES;
//    jokeImg.hidden = NO;
//    jokeImgBtn.hidden = NO;
    
    jokeImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapImage = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scanBigPhoto)];
    tapImage.numberOfTouchesRequired = 1;
    tapImage.numberOfTapsRequired = 1;
    [jokeImg addGestureRecognizer:tapImage];
    [tapImage release];

    [self rebuildView];
    
    //生成一张快速浏览图
    static float THUMBNAILWIDTH = 202.00;
    static float THUMBNAILHEIGHT = 140.00;

    UIImage *scanImg = [self thumbnailOfImage:image withWidth:THUMBNAILWIDTH withHeight:THUMBNAILHEIGHT];
    NSString *md5str = [jokeUrlForMd5 md5strLower:jokeUrlForMd5];
    NSString *imgFilePath = [SD_CACHES_FOLDER stringByAppendingPathComponent:[NSString stringWithFormat:@"small_%@",md5str]];
    
    NSLog(@"imgFilePath------ :%@",imgFilePath);
    
    NSData *imageData = UIImageJPEGRepresentation(scanImg, 0.5);
    Log(@"%@",imgFilePath);
    NSError *err = nil;
    if ( [imageData writeToFile:imgFilePath options:NSAtomicWrite error:&err]) {
        NSLog(@"缩略图 write success :%@",err);
    }else{
        NSLog(@"缩略图 write failed :%@",err);
    }
    [self imageDidFinishLoadingSoDecompress];
}

// Called on main
- (void)webImageManager:(SDWebImageManager *)imageManager didFailWithError:(NSError *)error {

    jokeImg.image = [UIImage imageNamed:@"loading_false.png"];
    //    jokeWebViewContainer.hidden = YES;
    //    jokeImg.hidden = NO;
//    jokeImgBtn.hidden = NO;
    [self rebuildView];
    [self imageDidFinishLoadingSoDecompress];
    
}
// Called on main
- (void)imageDecoder:(SDWebImageDecoder *)decoder didFinishDecodingImage:(UIImage *)image userInfo:(NSDictionary *)userInfo {
    // Finished compression so we're complete
    NSLog(@"33333");
    jokeImg.image = image;
}

#pragma mark –
#pragma mark ------thumbnail------

- (UIImage*)thumbnailOfImage:(UIImage*)image withWidth:(float)resWidth withHeight:(float)resHeight
{
    if(!image){
        return nil;
    }
    CGImageRef imageRef = [image CGImage];
    float _width = CGImageGetWidth(imageRef);
    float _height = CGImageGetHeight(imageRef);
    //    Log(@"test1: %f x %f",_width,_height);
    UIImage *thumb;
    if(_width<resWidth && _height<resHeight){
        thumb = [image copy];
        return thumb;
    }else{
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        float scaleWidth = resWidth/_width;
        float scaleHeight = resHeight/_height;
        float scaleMin = MAX(scaleWidth, scaleHeight);
        UIImage *scaleImg = [self resizeImage:image withScale:scaleMin];
        //        CGImageRef scaleImageRef = [scaleImg CGImage];
        //        Log(@"test2: %zu x %zu",CGImageGetWidth(scaleImageRef),CGImageGetHeight(scaleImageRef));
        CGRect rect = CGRectMake(0, 0, resWidth, resHeight);//创建矩形框
        //        Log(@"test3: %f x %f",rect.size.width,rect.size.height);
        UIImage *subImage = [self cutImage:scaleImg withRect:rect];
        //        CGImageRef subImageRef = [subImage CGImage];
        //        Log(@"test4: %zu x %zu",CGImageGetWidth(subImageRef),CGImageGetHeight(subImageRef));
        thumb = [subImage copy];
        [pool release];
        return [thumb autorelease];
    }
}

- (UIImage *)resizeImage:(UIImage *)image withScale:(float)scaleSize {
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

- (UIImage *)cutImage:(UIImage *)image withRect:(CGRect)rect {
    UIImage * subImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([image CGImage], rect)];
    return subImage;
}


@end





#pragma mark -------LikeStateBase Class-------
@implementation JPCLikeStateBase
-(id)init:(JokePageCell *)pOwner {
    self = [super init];
    if (self) {
        owner = pOwner;
    }
    return self;
}
-(void)JPCLSstart{
    owner.funnyBtn.tag = owner.jokePlaying.liked==1?1:0;
    owner.funnyBtn.image = owner.jokePlaying.liked==1?[UIImage imageNamed:@"action_good_2.png"]:[UIImage imageNamed:@"action_good_1.png"];
    owner.unfunnyBtn.tag = owner.jokePlaying.unliked==1?1:0;
    owner.unfunnyBtn.image = owner.jokePlaying.unliked==1?[UIImage imageNamed:@"action_bad_2.png"]:[UIImage imageNamed:@"action_bad_1.png"];
}
-(void)JPCLSlike{
    if( owner.funnyBtn.tag == 1 ){
        return;
    }
    owner.funnyBtn.tag = 1;
    owner.funnyBtn.image = [UIImage imageNamed:@"action_good_2.png"];
    int curGood = owner.funnyNum.tag;
    curGood++;
    owner.funnyNum.text = [NSString stringWithFormat:@"+%d",curGood];
    owner.funnyNum.tag = curGood;
    owner.jokePlaying.goodNum = curGood;
    if( owner.unfunnyBtn.tag == 1 ){
        owner.unfunnyBtn.tag = 0;
        owner.unfunnyBtn.image = [UIImage imageNamed:@"action_bad_1.png"];
        int curBad = owner.unfunnyNum.tag;
        curBad--;
        owner.unfunnyNum.text = [NSString stringWithFormat:@"-%d",curBad];
        owner.unfunnyNum.tag = curBad;
        owner.jokePlaying.badNum = curBad;
    }
    
    //+1动画
    UIImageView * plusOne = [[UIImageView alloc] initWithFrame:CGRectMake(owner.funnyBtn.frame.origin.x+20, owner.funnyBtn.frame.origin.y-30, 24 , 24)];
    plusOne.image = [UIImage imageNamed:@"plus.png"];
    plusOne.backgroundColor = [UIColor clearColor];
    plusOne.alpha = 1.0f;
    plusOne.hidden = YES;
    [owner.jokeInfoView addSubview:plusOne];
    plusOne.hidden = NO;
    [UIView animateWithDuration:1.0 animations:^{
        plusOne.alpha = 0.0f;
        plusOne.frame = CGRectMake(owner.funnyBtn.frame.origin.x+8, owner.funnyBtn.frame.origin.y-80, 48, 48);
    }completion:^(BOOL finished) {
        [plusOne removeFromSuperview];
        [plusOne release];
    }];
}
-(void)JPCLSunlike {
    if( owner.unfunnyBtn.tag == 1 ){
        return;
    }
    owner.unfunnyBtn.tag = 1;
    owner.unfunnyBtn.image = [UIImage imageNamed:@"action_bad_2.png"];
    int curBad = owner.unfunnyNum.tag;
    curBad++;
    owner.unfunnyNum.text = [NSString stringWithFormat:@"-%d",curBad];
    owner.unfunnyNum.tag = curBad;
    owner.jokePlaying.badNum = curBad;
    if( owner.funnyBtn.tag == 1 ){
        owner.funnyBtn.tag = 0;
        owner.funnyBtn.image = [UIImage imageNamed:@"action_good_1.png"];
        int curGood = owner.funnyNum.tag;
        curGood--;
        owner.funnyNum.text = [NSString stringWithFormat:@"+%d",curGood];
        owner.funnyNum.tag = curGood;
        owner.jokePlaying.goodNum = curGood;
    }
    
    //-1动画
    UIImageView * minusOne = [[UIImageView alloc] initWithFrame:CGRectMake(owner.unfunnyBtn.frame.origin.x+20, owner.funnyBtn.frame.origin.y-30, 24 , 24)];
    minusOne.image = [UIImage imageNamed:@"minus.png"];
    minusOne.backgroundColor = [UIColor clearColor];
    minusOne.alpha = 1.0f;
    minusOne.hidden = YES;
    [owner.jokeInfoView addSubview:minusOne];
    minusOne.hidden = NO;
    [UIView animateWithDuration:1.0 animations:^{
        minusOne.alpha = 0.0f;
        minusOne.frame = CGRectMake(owner.unfunnyBtn.frame.origin.x+8, owner.unfunnyBtn.frame.origin.y-80, 48, 48);
    }completion:^(BOOL finished) {
        [minusOne removeFromSuperview];
        [minusOne release];
    }];
}
@end

#pragma mark -------LikeStateLoading Class-------
@implementation JPCLikeStateLoading
-(void)JPCLSstart{
    owner.funnyBtn.image = [UIImage imageNamed:@"action_good_3.png"];
    owner.unfunnyBtn.image = [UIImage imageNamed:@"action_bad_3.png"];
}
-(void)JPCLSlike{
    //    [owner.owner baseShowHUD:@"正在加载,请稍后..." atY:10.0f];
    [owner.owner baseShowInfoHud:NSLocalizedString(@"正在加载,请稍候...", @"") andIsTop:NO];
}
-(void)JPCLSunlike {
    [owner.owner baseShowInfoHud:NSLocalizedString(@"正在加载,请稍候...", @"") andIsTop:NO];
}
@end

#pragma mark -------LikeStateEnable Class-------
@implementation JPCLikeStateEnable
-(void)JPCLSlike{
    [super JPCLSlike];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if( [owner.jokeManagerPlaying httpLikedSync:owner.jokePlaying.jokeId] ){
            owner.jokePlaying.liked = 1;
            [owner setLikeState:owner.likeStateDisable];
            [[DBManager sharedInstance] updateJoke:owner.jokeManagerPlaying.dbSort :owner.jokePlaying];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                int curGood = owner.funnyNum.tag;
                owner.funnyBtn.tag = 0;
                owner.funnyBtn.image = [UIImage imageNamed:@"action_good_1.png"];
                curGood--;
                owner.funnyNum.text = [NSString stringWithFormat:@"+%d",curGood];
                owner.funnyNum.tag = curGood;
                owner.jokePlaying.goodNum = curGood;
                //                [owner.owner baseShowHUD:@"网络错误，请稍后再试" atY:-60.0f];
                [owner.owner baseShowInfoHud:NSLocalizedString(@"网络错误，请稍后再试", @"") andIsTop:NO];
            });
        }
    });
}
-(void)JPCLSunlike {
    [super JPCLSunlike];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if( [owner.jokeManagerPlaying httpUnlikedSync:owner.jokePlaying.jokeId] ){
            owner.jokePlaying.unliked = 1;
            [owner setLikeState:owner.likeStateDisable];
            [[DBManager sharedInstance] updateJoke:owner.jokeManagerPlaying.dbSort :owner.jokePlaying];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                int curBad = owner.unfunnyNum.tag;
                owner.unfunnyBtn.tag = 0;
                owner.unfunnyBtn.image = [UIImage imageNamed:@"action_bad_1.png"];
                curBad--;
                owner.unfunnyNum.text = [NSString stringWithFormat:@"-%d",curBad];
                owner.unfunnyNum.tag = curBad;
                owner.jokePlaying.badNum = curBad;
                //                [owner.owner baseShowHUD:@"网络错误，请稍后再试" atY:-60.0f];
                //                [owner.owner baseShowMiddleHUD:NSLocalizedString(@"网络错误，请稍后再试", @"")];
                [owner.owner baseShowInfoHud:NSLocalizedString(@"网络错误，请稍后再试", @"") andIsTop:NO];
            });
        }
    });
}
@end

#pragma mark -------LikeStateDisable Class-------
@implementation JPCLikeStateDisable
-(void)JPCLSlike{
    [super JPCLSlike];
}
-(void)JPCLSunlike {
    [super JPCLSunlike];
}
@end

#pragma mark -------JABUserStateBase Class-------
@implementation JPCUserStateBase
-(id)init:(JokePageCell *)pOwner {
    self = [super init];
    if (self) {
        owner = pOwner;
    }
    return self;
}
@end

@implementation JPCUserStateLogin
-(void)JPCUSlike{
    [owner.currentLikeState JPCLSlike];
}
-(void)JPCUSunlike{
    [owner.currentLikeState JPCLSunlike];
}
@end

@implementation JPCUserStateLogout
-(void)JPCUSlike{
    [owner.owner JPClogin];
}
-(void)JPCUSunlike{
    [owner.owner JPClogin];
}
@end